
"format a page with an accordion"

from whiff.middleware import misc
from whiff import gateway

IDENTITIES_VARIABLE = "mooAccordion.identities"
SCRIPTS_VARIABLE = "moo.DomReadyList"

class mooAccordion(misc.utility):
    def __init__(self, page,
                 variable=IDENTITIES_VARIABLE,
                 ):
        # xxxx eventually add moo parameter flags
        self.page = page
        self.variable = variable
    def __call__(self, env, start_response):
        # add a list to store ids of togglers and segments
        variable = self.param_value(self.variable, env)
        env = env.copy()
        env[variable] = []
        # evaluate the page (and populate the list)
        page = self.param_value(self.page, env)
        # generate javascript using the ids
        pairs = env[variable]
        js = self.accordionJavascript(pairs, env)
        # deliver page and javascript
        #payload = page+js
        payload = '<div style="margin:0px;padding:4px">%s</div>' % page
        # xxxx quick fix: clean this up someday.
        #env[SCRIPTS_VARIABLE].append(js)
        resource_path = ["local", SCRIPTS_VARIABLE]
        scripts = gateway.getResource(env, resource_path)
        scripts.append(js)
        gateway.putResource(env, resource_path, scripts)
        return self.deliver_page(payload, env, start_response)
    def accordionJavascript(self, pairs, env):
        return "".join(list(self.accordionJavascriptGen(pairs,env)))
    def accordionJavascriptGen(self, pairs, env):
        #yield "\n<script>\n"
        varname = gateway.getResource(env, ["freshName", "accordion"])
        yield "var "
        yield varname
        yield " = new Accordion(["
        inside = False
        for (togglerid, segmentid) in pairs:
            if inside:
                yield ", "
            inside = True
            yield '$("'
            yield togglerid
            yield '")'
        yield "], ["
        inside = False
        for (togglerid, segmentid) in pairs:
            if inside:
                yield ", "
            inside = True
            yield '$("'
            yield segmentid
            yield '")'
        yield "]);\n"
        #yield "\n</script>\n"

__middleware__ = mooAccordion
